package com.cetool.autocms.common;

import cn.hutool.core.date.DatePattern;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * 阿里easyExcel时间转换器
 *
 * @author 端木超群
 * @date 2021/1/12
 */
public class LocalDateTimeConverter implements Converter<LocalDateTime> {

    /**
     * 导出excel时间转换格式
     */
    private final String dateFormat;

    /**
     * 有参构造器
     *
     * @param dateFormat 时间转换格式
     */
    public LocalDateTimeConverter(String dateFormat) {
        this.dateFormat = dateFormat;
    }


    @Override
    public Class supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty,
                                           GlobalConfiguration globalConfiguration) throws Exception {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN);
        LocalDate localDate = LocalDate.parse(cellData.getStringValue(), dateTimeFormatter);
        return LocalDateTime.of(localDate, LocalTime.of(0, 0));
    }

    @Override
    public CellData convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new CellData(localDateTime.format(DateTimeFormatter.ofPattern(dateFormat)));
    }
}
